package vn.vfriends.vbox.security.filter;

import io.buji.pac4j.ClientFilter;
import java.util.Arrays;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.oauth.profile.google2.Google2Profile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.model.Provider;
import vn.vfriends.vbox.model.Role;
import vn.vfriends.vbox.model.RoleCode;
import vn.vfriends.vbox.model.User;
import vn.vfriends.vbox.service.RoleService;
import vn.vfriends.vbox.service.UserService;
import vn.vfriends.vbox.util.ServiceUtil;

/**
 *
 * @author tuancn
 */
public class VBoxClientFilter extends ClientFilter {
    
    private static final Logger logger = LoggerFactory.getLogger(VBoxClientFilter.class);
    
    @Override
    protected boolean onLoginSuccess(final AuthenticationToken token, final Subject subject,
                                     final ServletRequest request, final ServletResponse response) throws Exception {
        Provider provider;
        if(request.getParameter("client_name").equals("Google2Client")) {
            provider = Provider.GOOGLE;
        } else {
            throw new Exception("Unknow provider");
        }
        
        UserService userService = ServiceUtil.getUserService();
        RoleService roleService = ServiceUtil.getRoleService();
        
        CommonProfile commonProfile = (CommonProfile) subject.getPrincipals().asList().get(1);
        String username = "";
        String location = "";
        if(commonProfile instanceof Google2Profile) {
            username = commonProfile.getEmail();
            location = ((Google2Profile)commonProfile).getLocale().toString();
        } else {
            username = commonProfile.getUsername();
            location = commonProfile.getLocation();
        }
        
        User user = userService.find(username, provider.toString());
        if(user == null) {
            user = new User();
            user.setUsername(username);
            user.setName(commonProfile.getDisplayName());
            user.setEmail(commonProfile.getEmail());
            user.setGender(User.Gender.valueOf(commonProfile.getGender().toString()));
            user.setLocation(location);
            user.setOwnId(commonProfile.getId());
            user.setPictureUrl(commonProfile.getPictureUrl());
            user.setProvider(provider);
            user.setActivated(true);
            
            Role userRole = roleService.findByCode(RoleCode.USER);
            user.setRoles(Arrays.asList(userRole));
            
            user = userService.create(user);
        }
        
        SecurityUtils.getSubject().getSession().setAttribute("LOGGED_USER", user);
        
        issueSuccessRedirect(request, response);
        return false;
    }
}
